<template>
    <!-- 编辑患者基础资料弹框 -->
    <el-dialog class="x-dialog update-dialog" :visible.sync="visibleFlag" :title="title" width="70%" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" @close="onCloseDialog()">
        <!-- body -->
        <section class="x-dialog__body" v-loading="loading" element-loading-text="" element-loading-background="rgba(#fff, .5)" element-loading-spinner="el-icon-loading">
            <el-form class="x-form x-form--flex" ref="xForm" :model="form" :rules="rules" label-width="100px" size="small">
                <el-form-item label="姓名" prop="patientName">
                    <el-input class="o-inp--full" type="text" v-model.trim="form.patientName" autocomplete="off" placeholder="姓名" :disabled="!isSub"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="patientSex">
                    <el-radio-group v-model="form.patientSex" @change="changeSexValue(form.patientSex)">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="生日" prop="patientBirthday">
                     <el-date-picker class="o-inp-datetime--full" v-model="form.patientBirthday" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" disabled>
                    </el-date-picker>
                </el-form-item> -->
                <el-form-item label="身高(cm)" prop="patientHeight">
                    <el-input class="o-inp--full" type="text" v-model.trim="form.patientHeight" placeholder="身高"></el-input>
                </el-form-item>
                <el-form-item prop="patientProfession" label="职业">
                    <el-select class="o-select--full" v-model="form.patientProfession" placeholder="请选择职业" clearable>
                        <el-option v-for="(item,index) in occupationList" :key="index" :label="item.occupationName" :value="item.occupationName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="体重(kg)" prop="patientWeight">
                    <el-input class="o-inp--full" type="text" v-model.trim="form.patientWeight" placeholder="体重"></el-input>
                </el-form-item>
                <el-form-item prop="patientPhone" label="手机号码">
                    <!-- 自主开方-远程搜索 -->
                    <el-autocomplete v-if="isSub" class="o-inp--full" popper-class="suggestions-popover" v-model.trim="form.patientPhone" placeholder="手机号码" :fetch-suggestions="(query,cb) => queryKeyword(query, cb, 'mobile')" :trigger-on-focus="true" :debounce=0 @select="v => onSelectQuery(v, 'mobile')">
                        <template slot-scope="{ item }">
                            <div class="item">
                                <div>{{item.patientName}}（{{item.patientIdcard}}）</div>
                                <div>tel：{{item.patientPhone}}</div>
                            </div>
                        </template>
                    </el-autocomplete>
                    <el-input v-else class="o-inp--full" type="text" v-model.trim="form.patientPhone" autocomplete="off" placeholder="手机号码" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item prop="patientIdcard" label="身份证">
                    <!-- 自主开方-远程搜索 -->
                    <el-autocomplete v-if="isSub" class="o-inp--full" popper-class="suggestions-popover" v-model.trim="form.patientIdcard" placeholder="身份证" :fetch-suggestions="(query,cb) => queryKeyword(query, cb, 'patientIdcard')" :trigger-on-focus="true" :debounce=0 @select="v => onSelectQuery(v, 'patientIdcard')">
                        <template slot-scope="{ item }">
                            <div class="item">
                                <div>{{item.patientName}}（{{item.patientIdcard}}）</div>
                                <div>tel：{{item.patientPhone}}</div>
                            </div>
                        </template>
                    </el-autocomplete>
                    <el-input v-else class="o-inp--full" type="text" v-model.trim="form.patientIdcard" placeholder="身份证" maxlength="18" disabled></el-input>
                </el-form-item>
                <el-form-item prop="patientMaritalStatus" label="籍贯">
                    <el-input class="o-inp--full" type="text" v-model.trim="form.patientMaritalStatus" placeholder="籍贯"></el-input>
                </el-form-item>

                <!-- 自主开方版本-地址 -->
                <el-form-item v-if="isSub" prop="autonomousAddress" label="住址" :rules="[{ required: isSub, message: '住址为必填', trigger: 'blur' }]">
                    <v-distpicker @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" :province="form.province" :city="form.city" :area="form.district"></v-distpicker>
                    <el-input class="o-inp--full" type="text" v-model.trim="form.autonomousAddress" placeholder="请输入详细地址"></el-input>
                </el-form-item>
                <!-- 正常问诊版本-地址 -->
                <el-form-item v-else prop="patientAddress" label="住址" :rules="[{ required: isSub, message: '住址为必填', trigger: 'blur' }]">
                    <el-input class="o-inp--full" type="text" v-model.trim="form.patientAddress" placeholder="住址"></el-input>
                </el-form-item>

                <el-form-item label="特殊情况" prop="isChildOption">
                    <el-select class="o-select--full" v-model="form.isChildOption" placeholder="请选择" :disabled="form.patientSex != 0" clearable>
                        <el-option v-for="(item,index) in $dict.specialIds" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="婚否" prop="isMarried">
                    <el-select class="o-select--full" v-model="form.isMarried" placeholder="请选择" clearable>
                        <el-option v-for="(item,index) in $dict.marriedIds" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </section>
        <!-- footer -->
        <div slot="footer" class="x-dialog__footer">
            <el-button class="o-btn" :loading="loading" type="text" size="small" @click="onCloseDialog()">取消</el-button>
            <el-button class="o-btn" :loading="loading" type="primary" size="small" @click="onSubmitForm('xForm')">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import VDistpicker from 'v-distpicker'
    export default {
        components: { VDistpicker },
        props: {
            isSub: {
                type: Boolean,
                default: false
            }, // 是否自主开方
        },
        data() {
            var validateIdCard = function(rule, value, callback) {
                let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

                if (!value) {
                    callback('身份证号为必填')
                } else if (value.length != 18 || !reg.test(value)) {
                    callback('身份证号不正确')
                } else {
                    callback()
                }
            };


            return {
                patientId: '',
                title: '编辑患者基础资料',
                visibleFlag: false,
                loading: false,
                form: {
                    patientName: '',
                    patientIdcard: '',
                    patientPhone: '',
                    patientSex: 0,
                    patientProfession: '',
                    patientBirthday: '',
                    patientHeight: '',
                    patientWeight: '',
                    isMarried: '',
                    patientMaritalStatus: '',
                    patientAddress: '',
                    isChildOption: '',
                    autonomousAddress: '',
                    addressCity: '',
                    city: '',
                    district: '',
                    province: '',
                    paymentMethod: '',
                },
                rules: {
                    patientName: [{ required: true, message: '姓名为必填', trigger: 'blur' }],
                    // patientBirthday: [{ required: true, message: '生日为必填', trigger: 'blur' }],
                    patientIdcard: [{ required: true, validator: validateIdCard, trigger: 'change' }],
                    patientPhone: [
                        { required: true, message: '手机号码为必填', trigger: 'blur' },
                        { validator: this.$validate.validateMobile, trigger: 'blur' }
                    ],
                },
                occupationList: [],
            }
        },
        methods: {
            onOpen(id = '', data = {}) {
                this.visibleFlag = true;
                this.loading = false;
                this.getOccupationList();

                this.patientId = id;
                this.setFormdata(data);
            },
            setFormdata(data = {}) {
                for (let k in this.form) {
                    if (k == 'patientSex') {
                        this.form[k] = data[k] || data[k] === 0 ? Number(data[k]) : 1;
                    } else if (k == 'addressCity') {
                        setTimeout(() => {
                            let adr = []
                            if (data.addressCity) adr = data.addressCity.split(' ')

                            this.form.province = adr[0] || ''
                            this.form.city = adr[1] || ''
                            this.form.district = adr[2] || ''
                        }, 100)
                    } else {
                        this.form[k] = data[k] || '';
                    }
                }

                this.$refs.xForm && this.$refs.xForm.clearValidate();
            },
            changeSexValue(value) {
                if (value != 0) this.form.isChildOption = '';
            },
            getOccupationList() { //获取职业列表
                let para = {
                    webToken: this.$authInfo.webToken()
                };

                this.$ajax.getOccupationList(para).then(res => {
                    this.occupationList = res.data.list
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            onCloseDialog(flag = false) {
                this.$refs.xForm && this.$refs.xForm.resetFields();

                this.visibleFlag = false;

                this.$emit('closed', flag);
            },
            // 提交修改
            onSubmitForm(refName) {
                this.loading = true;

                if (this.isSub) {
                    // 属于自主开方
                    this.updatePatientByAuto(refName)
                } else {
                    this.$refs[refName].validate(valid => {
                        if (valid) {
                            let params = {
                                id: this.patientId,
                                webToken: this.$authInfo.webToken()
                            };

                            for (let k in this.form) {
                                params[k] = this.form[k]
                            }

                            params.patientBirthday = this.setIdCard(params.patientIdcard)

                            this.$ajax.updateInquiryPatientInfo(params).then(res => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success'
                                })
                                this.loading = false;
                                this.$emit('submited', true);
                                this.onCloseDialog(true);
                            }).catch(err => {
                                this.$message.closeAll();
                                this.$message.error(err.msg);

                                this.loading = false;
                            })
                        } else {
                            this.loading = false;
                        }
                    })
                }
            },
            // 远程搜索
            queryKeyword(query, callback, type) {
                let params = {};

                params[type] = query || '';

                if (type == 'mobile' && this.form.patientIdcard) params.patientIdcard = this.form.patientIdcard;
                if (type == 'patientIdcard' && this.form.patientPhone) params.mobile = this.form.patientPhone;


                setTimeout(() => {
                    this.$ajax.queryPatientData(params).then(res => {
                        let result = res.data.list || [];
                        setTimeout(() => {
                            if (result && result.length > 0) {
                                callback(result)
                            } else {
                                callback([]);
                            }
                        }, 200)
                    }).catch(err => {
                        callback([]);
                        this.$util.message(err.msg);
                    })
                });
            },
            onSelectQuery(data = {}) {
                if (!data || data.id == -1) return;

                this.patientId = data.id;

                for (let k in this.form) {
                    if (data[k] || data[k] === 0) {
                        if (['autonomousAddress'].includes(k)) {
                            if (this.isSub) {
                                this.form[k] = data[k] || '';
                            } else {
                                continue;
                            }
                        } else if (k == 'patientAddress') {
                            if (this.isSub) {
                                continue
                            } else {
                                this.form[k] = data[k] || '';
                            }
                        } else if (k == 'addressCity') {
                            if (!this.isSub) {
                                continue
                            } else {
                                let addr = this.form[k] ? this.form[k].split(' ') : [];
                                this.form.province = addr[0] || '';
                                this.form.city = addr[1] || '';
                                this.form.district = addr[2] || '';
                            }
                        } else {
                            if (k == 'patientSex') {
                                this.form[k] = Number(data[k]);
                            } else {
                                this.form[k] = data[k] || '';
                            }
                        }


                    }
                }

                this.$refs.xForm.validate(valid => {})
            },
            // 自主开方-提交患者信息
            updatePatientByAuto(refName) {
                if (this.isSub) { // 自主开方需判断省市区地址
                    if (this.form.province && this.form.province != '省' && this.form.city && this.form.city != '市' && this.form.district && this.form.district != '区') {
                        this.form.addressCity = `${this.form.province} ${this.form.city} ${this.form.district}`
                    } else {
                        this.$util.message('请选择省市区')
                        this.loading = false;
                        return false;
                    }
                }



                this.$refs[refName].validate(valid => {
                    if (valid) {
                        let params = {};

                        if (this.patientId) params.patientId = this.patientId;
                        if (sessionStorage.autoLogId) params.logId = Number(sessionStorage.autoLogId);

                        for (let k in this.form) {
                            params[k] = this.form[k]
                        }

                        if (this.isSub) params.paymentMethod = 1; // 自主开方，限定只有自费类型

                        params.patientBirthday = this.setIdCard(params.patientIdcard)

                        this.$ajax.updatePatientInfoByAuto(params).then(res => {
                            this.loading = false;
                            this.$util.message(res.msg, 'success');

                            this.$emit('submited', {
                                patientId: res.data.patientId,
                                logId: res.data.logId
                            });

                            this.onCloseDialog(true);
                        }).catch(err => {
                            this.loading = false;

                            this.$util.message(err.msg);
                        })
                    } else {
                        this.loading = false;
                    }
                })
            },
            onChangeProvince(a) { //选择--省
                this.form.province = a.value
            },
            onChangeCity(a) { //选择--市区
                this.form.city = a.value
            },
            onChangeArea(a) { //选择--区
                this.form.district = a.value
            },
            setIdCard(value) {
                let idcard = value || this.form.patientIdcard;
                if (idcard && idcard.length == 18) {
                    var reg = /\d{1,6}(\d{1,4})(\d{1,2})(\d{1,2})/;

                    let result = idcard.match(reg);

                    return `${result[1]}-${result[2]}-${result[3]}`
                } else {
                    return '';
                }
            }
        }
    }
</script>

<style lang="scss" src="./checkDialogStyle.scss"></style>